<script setup>
import { ref } from 'vue';

const mediaRecorder = ref(null);
const audioChunks = ref([]);
const audioUrl = ref(null);
const isRecording = ref(false);
const hasRecording = ref(false);

function startRecording() {
  navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then((stream) => {
      mediaRecorder.value = new MediaRecorder(stream);
      mediaRecorder.value.ondataavailable = (event) => {
        audioChunks.value.push(event.data);
      };
      mediaRecorder.value.onstop = () => {
        const audioBlob = new Blob(audioChunks.value);
        audioUrl.value = URL.createObjectURL(audioBlob);
        audioChunks.value = []; // 清空chunks数组，为下一次录音准备
        hasRecording.value = true; // 有录音可以播放了
      };
      mediaRecorder.value.start();
      isRecording.value = true; // 开始录音状态更新
    })
    .catch((error) => console.error('Error accessing the microphone:', error));
}

function stopRecording() {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop();
    isRecording.value = false; // 停止录音状态更新
  }
}

function playRecording() {
  if (audioUrl.value) {
    const audio = new Audio(audioUrl.value);
    audio.play();
  }
}
</script>

<template>
  <div>
    <button @click="startRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <button @click="playRecording" :disabled="!hasRecording">播放录音</button>
  </div>
</template>
